class Shop::SkusController < ShopController
  before_action :set_spu

  def index
    @skus = @spu.skus.page(params[:page]).per(params[:per])
  end

  def new
    @sku = Sku.new
  end

  def create
    @sku = @spu.skus.build sku_params
    if Sku.is_exit? @spu, params[:sku_option_values]
      redirect_to shop_spu_skus_path(@spu), notice: '已存在该SKU组合' and return
    end
    if @sku.save
      @sku.update_option_values(params[:sku_option_values])
      @sku.spu.update_column("stock", @sku.spu.stock + @sku.on_hand_count)
      redirect_to shop_spu_skus_path(@spu)
    else
      render :new
    end
  end

  def edit
    @sku = Sku.find params[:id]
  end
  
  def update
    @sku = Sku.find params[:id]
    if not Sku.is_exit? @spu, params[:sku_option_values]
      @sku.update_option_values(params[:sku_option_values])
    end
    sku_pre_stock = @sku.on_hand_count
    if @sku.update sku_params
      if sku_pre_stock != @sku.on_hand_count
        temp_stock = sku_pre_stock - @sku.on_hand_count
        if temp_stock < 0
          temp_stock = 0 - temp_stock
        end
        @sku.spu.update_column("stock", @sku.spu.stock + temp_stock)
      end
      redirect_to shop_spu_skus_path(@spu)
    else
      render :edit
    end
  end
  
  def destroy
    @sku = Sku.find params[:id]
    if @sku.destroy
      redirect_to shop_spu_skus_path(@spu), notice: '删除成功.'
    else
      redirect_to shop_spu_skus_path(@spu), notice: '删除失败.'
    end
  end
  
  private

  def set_spu
    @spu = Spu.find params[:spu_id]
  end

  def sku_params
    params.require(:sku).permit(:name, :avatar, :cost_price, :sale_price, :on_hand_count, :promotion_price)
  end
  
end
